import {
  createColumn,
  deleteColumnById,
  queryColumnList,
  updateColumnById,
} from '@/service/article-column';
import { EditOutlined, EllipsisOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { App, Button, Card, Dropdown, List, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import ColumnModal from './components/ColumnModal';
import styles from './index.less'

const ColumnList: React.FC = () => {
  const { modal } = App.useApp();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser || {};

  // 专栏列表
  const [dataSource, setDataSource] = useState([]);

  // 操作标识
  const [operateType, setOperateType] = useState('');
  const [open, setOpen] = useState(false);
  const [modalInfo, setModalInfo] = useState({});

  const queryColumn = async () => {
    const res = await queryColumnList();
    setDataSource(res || []);
  };

  // 新建、编辑专栏 - 弹窗
  const prevOperateColumn = (type, item) => {
    setOperateType(type);
    setModalInfo(item || {});
    setOpen(true);
  };

  // 新建、编辑专栏 - 提交
  const columnOperateFinish = async (values) => {
    let res = null;
    if (operateType === 'add') {
      res = await createColumn(values);
    } else if (operateType === 'edit') {
      res = await updateColumnById(modalInfo.id, values);
    }

    if (res) {
      message.success('操作成功');
      // 刷新列表
      queryColumn();
      setOpen(false);
      setModalInfo({});
    }
  };

  // 删除专栏
  const deleteColumn = (item) => {
    modal.confirm({
      title: '删除提示',
      content: `确定删除标题为《${item.title}》的专栏吗？删除后专栏里的文章不会被删除，但专栏的关联关系会被删除`,
      onOk: async () => {
        const res = await deleteColumnById(item.id);
        if (res) {
          message.success('操作成功');
          // 刷新列表
          queryColumn();
        }
      },
    });
  };

  // 跳转到专栏管理
  const goToColumnDetail = (item) => {
    history.push(`/column/detail/${item.id}`);
  };

  useEffect(() => {
    queryColumn();
  }, []);

  return (
    <PageContainer
      header={{
        title: false,
        extra:
          currentUser?.roleWeight < 3
            ? [
                <Button key="publish" type="primary" onClick={() => prevOperateColumn('add')}>
                  新建专栏
                </Button>,
              ]
            : null,
      }}
    >
      <List
        grid={{
          gutter: 16,
          column: 3,
          sm: 1,
          md: 2,
          lg: 2,
        }}
        dataSource={dataSource}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card
              title={item.title}
              hoverable={true}
              extra={<div>文章数：{item.count}</div>}
              actions={[
                <div key="time">
                  {item.createdTime ? moment(item.createdTime).format('YYYY-MM-DD') : ''}
                </div>,
                currentUser?.roleWeight < 3 ? (
                  <EditOutlined key="edit" onClick={() => prevOperateColumn('edit', item)} />
                ) : null,
                currentUser?.roleWeight < 3 ? (
                  <Dropdown
                    key="ellipsis"
                    menu={{
                      items: [
                        {
                          key: 'content',
                          label: '专栏管理',
                          onClick: () => goToColumnDetail(item),
                        },
                        {
                          key: 'delete',
                          label: '删除',
                          onClick: () => deleteColumn(item),
                        },
                      ],
                    }}
                  >
                    <EllipsisOutlined />
                  </Dropdown>
                ) : null,
              ]}
            >
              <div className={styles.descWrapper}>{item.description}</div>
            </Card>
          </List.Item>
        )}
      />
      <ColumnModal
        modalInfo={modalInfo}
        operateType={operateType}
        open={open}
        onOpenChange={setOpen}
        onFinish={columnOperateFinish}
      />
    </PageContainer>
  );
};

export default ColumnList;
